package org.anderground.editor.gui.menubar;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JMenu;
import javax.swing.JMenuItem;

import org.anderground.core.Logger;
import org.anderground.core.model.Station;
import org.anderground.core.model.Tunnel;
import org.anderground.editor.gui.properties.SelectionListener;
import org.anderground.editor.model.EditorModel;
import org.anderground.editor.tools.ToolsRegistry;
import org.anderground.modules.editor.tools.EditorTool;


@SuppressWarnings("serial")
public class ToolsMenu extends JMenu implements SelectionListener {
	private List<Class<? extends EditorTool>> tools = new ArrayList<Class<? extends EditorTool>>();
	private List<Station> selectedStations = new ArrayList<Station>();
	private List<Tunnel> selectedTunnel = new ArrayList<Tunnel>();

	public ToolsMenu() {
		super("Tools");
		tools.addAll(ToolsRegistry.getTools());
		for (final Class<? extends EditorTool> tool : tools) {
			try {

				JMenuItem toolItem = new JMenuItem(tool.newInstance().getName());
				this.add(toolItem);
				toolItem.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent arg0) {
						try {
							tool.newInstance().call(
									EditorModel.getInstance().getData(),
									selectedStations.toArray(new Station[0]),
									selectedTunnel.toArray(new Tunnel[0]));
						} catch (InstantiationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				});
			} catch (Exception e) {
				Logger.w(tool.getName() + " can't be instantiated");
			}
		}
	}

	@Override
	public void onSelectionChanged(List<Station> selectedStations,
			List<Tunnel> selectedTunnel) {
		this.selectedStations = selectedStations;
		this.selectedTunnel = selectedTunnel;

	}

}
